package com.nbsaas.boot;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

public class SignatureValidator {

    public static boolean isValid(String shopCodeEncoded, String ts, String token, String sign) {
        try {
            // 1. URL解码 shopCode
            String shopCode = URLDecoder.decode(shopCodeEncoded, "UTF-8");

            // 2. 拼接原始字符串
            String raw = shopCode + ts + token;

            // 3. 计算 MD5 签名
            String expectedSign = md5(raw);

            // 4. 比较签名（不区分大小写）
            return expectedSign.equalsIgnoreCase(sign);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String md5(String input) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(input.getBytes(StandardCharsets.UTF_8));

        // 转换为十六进制字符串
        StringBuilder hex = new StringBuilder();
        for (byte b : digest) {
            String h = Integer.toHexString(0xff & b);
            if (h.length() == 1) hex.append('0');
            hex.append(h);
        }
        return hex.toString();
    }

    // 示例调用
    public static void main(String[] args) throws Exception {
        String shopCodeEncoded = "SD0011"; // 示例值，应为URL编码形式
        String ts = "1751426706";
        String token = "hxGHyESX0gNYufGhFQKctl90Rs26OxOP";
        String sign = "9c0f15b58cc1e8e5098f187a248ba5a8"; // 示例签名

        boolean result = isValid(shopCodeEncoded, ts, token, sign);
        System.out.println("签名验证结果: " + result);
    }
}
